/**
 * 
 */
package com.yst.metho.web.application.pointage;

import java.util.Calendar;

import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.NamingException;

import nextapp.echo2.app.Alignment;
import nextapp.echo2.app.Row;

import com.yst.metho.web.application.SuiviProdApp;
import com.yst.metho.web.application.utils.ExceptionMgt;
import com.yst.metho.web.application.utils.Locator;
import com.yst.suivi.data.user.User;
import com.yst.suivi.util.DateUtil;

import echopointng.DateChooser;
import echopointng.model.CalendarEvent;
import echopointng.model.CalendarSelectionListener;

/**
 * @author perso
 * 
 */
public class MyActivityViewPane extends Row implements CalendarSelectionListener
{
	private Calendar mSelectedDay;

	private DateChooser mDtChooser;

	private MyActivityPane mPointagePane;

	public MyActivityViewPane(Calendar initDay) throws FinderException, NamingException, CreateException
	{
		super();
		setAlignment(Alignment.ALIGN_TOP);
		mSelectedDay = initDay;
		buildWeekView();
		mDtChooser = new DateChooser();
		add(mDtChooser);
		mDtChooser.getModel().addListener(this);
	}

	private void buildWeekView() throws FinderException, NamingException, CreateException
	{
		MyActivityModel model = new MyActivityModel();
		// Recuperation de la date du premier jour de la semaine.
		Calendar currentDay = (Calendar) mSelectedDay.clone();
		currentDay = DateUtil.getFirstDayOfWeek(currentDay);
		com.yst.suivi.services.pointage.PointageView pointageService = Locator.getPointageView();
		User usr = Locator.getUserView().findByLogin(SuiviProdApp.getApp().getLoggedUser());
		String sJour, sMois, sAnnee;
		// recuperation de tous les pointages de la semaine
		for (int jour = 0; jour < 6; jour++)
		{
			sJour = Integer.toString(currentDay.get(Calendar.DAY_OF_MONTH));
			sMois = Integer.toString(currentDay.get(Calendar.MONTH));
			sAnnee = Integer.toString(currentDay.get(Calendar.YEAR));
			model.addDay(pointageService.findByDate(sJour, sMois, sAnnee, usr), currentDay);

			currentDay.add(Calendar.DAY_OF_MONTH, 1);
		}
		int index = -1;
		if (null != mPointagePane)
		{
			remove(mPointagePane);
			mPointagePane.dispose();
			index = 0;
		}
		mPointagePane = new MyActivityPane(model, new MyActivityCellRenderer());
		add(mPointagePane, index);
	}

	public void displayedDateChange(CalendarEvent arg0)
	{
	}

	public void selectedDateChange(CalendarEvent event)
	{
		try
		{
			mSelectedDay = event.getCalendar();
			buildWeekView();
		}
		catch (FinderException e)
		{
			ExceptionMgt.manage(e);
		}
		catch (NamingException e)
		{
			ExceptionMgt.manage(e);
		}
		catch (CreateException e)
		{
			ExceptionMgt.manage(e);
		}
	}

}
